<template>
  <!-- 视频流 -->
  <div class="absolute w-full h-full top-0 left-0 z-10">
    <video
      ref="bgVideo"
      class="w-full h-full"
      autoplay
      playsinline
      muted
      controls
    ></video>
  </div>
  <!-- 输入框 -->
  <div
    v-if="pageView === 0 && showTextarea"
    class="absolute w-100vw h-26.5vh top-27.7vh flex justify-center"
  >
    <div class="w-26.5vh h-26.5vh z-3 flex justify-center items-center">
      <div class="w-84% h-41.5% textarea">
        <div class="flex flex-col gap-1.5 p-2 text-11px text-#e2be8b">
          <textarea
            ref="textareaRef"
            class="w-full h-full bg-transparent py-1 border-0"
            style="box-sizing: border-box"
            v-model="message"
            placeholder="请输入内容"
            rows="3"
            maxlength="20"
            placeholder-style="color: #e2be8b;"
            placeholder-class="text-#e2be8b"
          ></textarea>
          <div class="flex justify-between">
            <span>{{ message.length }}/20</span>
            <span @click="message = ''">清空</span>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- 线框 -->
  <div
    class="absolute w-full h-full top-0 left-0 z-2"
    @touchstart="onTouchStart"
    @touchend="onTouchEnd"
  >
    <!-- 拍摄框 -->
    <div class="w-full">
      <div class="relative mt-8vh flex justify-center">
        <van-image
          width="94%"
          fit="fill"
          src="./ui/border.png"
          :show-error="false"
          :show-loading="false"
        />

        <!-- page3: 选择颜色渲染 -->
        <div
          v-if="pageView === 2 && !isFinished"
          class="absolute top-0 left-5% w-90% h-full"
        >
          <span
            v-for="(color, idx) in colorList"
            :key="idx"
            class="absolute"
            :style="`left: ${color.left};top: ${color.top};width: 16%`"
          >
            <van-image
              width="100%"
              fit="fill"
              :src="colorName === color.name ? color.imgH : color.img"
              @click="updateColor(color)"
              :show-error="false"
              :show-loading="false"
            />
          </span>
        </div>
        <!-- logo -->
        <div class="absolute top-0">
          <!-- logo -->
          <van-image
            width="25vw"
            fit="fill"
            src="./ui/LOGO.png"
            @click="updateView(1)"
            :show-error="false"
            :show-loading="false"
          />
        </div>
        <!-- 按钮 -->
        <template v-if="pageView === 0">
          <!-- 开始按钮 -->
          <div v-if="message.length > 0" class="absolute bottom-[2%]">
            <van-image
              v-if="!isInputEnd"
              width="40vw"
              fit="fill"
              src="./ui/start_h.png"
              @click="isInputEnd = true"
              :show-error="false"
              :show-loading="false"
            />
            <van-image
              v-else
              width="40vw"
              fit="fill"
              src="./ui/btn02.png"
              @click="updateView(1)"
              :show-error="false"
              :show-loading="false"
            />
          </div>
          <!-- 点击输入按钮 -->
          <div v-if="message.length <= 0" class="absolute bottom-[2%]">
            <van-image
              width="40vw"
              fit="fill"
              src="./ui/btn01.png"
              @click="textareaRef?.focus()"
              :show-error="false"
              :show-loading="false"
            />
          </div>
        </template>
        <template v-if="pageView === 2">
          <div v-if="!isFinished" class="absolute bottom-[2%]">
            <van-image
              width="40vw"
              fit="fill"
              src="./ui/start_h.png"
              @click="isFinished = true"
              :show-error="false"
              :show-loading="false"
            />
          </div>
          <div
            v-else
            class="absolute bottom-[-10%] flex flex-col items-center gap-3"
          >
            <van-image
              width="10vw"
              fit="fill"
              src="./ui/tips.png"
              @click="updateView(1)"
              :show-error="false"
              :show-loading="false"
            />
            <van-image
              width="40vw"
              fit="fill"
              src="./ui/btn03.png"
              @click="updateView(1)"
              :show-error="false"
              :show-loading="false"
            />
          </div>
        </template>
      </div>
    </div>
    <!-- end -->
  </div>

  <!-- 3D部分 -->
  <div>
    <TresCanvas
      window-size
      :outputColorSpace="THREE.SRGBColorSpace"
      :toneMapping="THREE.NoToneMapping"
      :clearAlpha="0"
    >
      <Suspense>
        <TheExperience2
          ref="exRef"
          :craneColor="craneColor"
          :pageView="pageView"
          :isFlying="isFlying"
          @updateView="updateView"
          @showTextarea="showTextarea = true"
          @released="onFinished"
        />
      </Suspense>
    </TresCanvas>
  </div>
</template>

<script setup lang="ts">
import * as THREE from "three";
import { onMounted, ref, shallowRef } from "vue";
import { TresCanvas } from "@tresjs/core";
// import { OrbitControls } from "@tresjs/cientos";
import { colorList } from "../config";

import TheExperience2 from "../components/TheExperience2.vue";

const bgVideo = ref(null);
const textareaRef = shallowRef<HTMLTextAreaElement | null>(null);
const exRef = shallowRef<InstanceType<typeof TheExperience2> | null>(null);
const pageView = ref(0);
const message = ref("");
const colorName = ref("yellow");
const craneColor = ref("#e7ba81");
const showTextarea = ref(false);
const isInputEnd = ref(false);
const isFinished = ref(false);
const isFlying = ref(false);
const startY = ref(0);
const endY = ref(0);

onMounted(() => {
  const { innerWidth, innerHeight } = window;
  navigator.mediaDevices
    .getUserMedia({
      video: {
        facingMode: "environment",
        frameRate: { min: 60, max: 60 },
        width: innerHeight * 2,
        height: innerWidth * 2,
      },
    })
    .then((stream) => {
      const video = bgVideo?.value as any;
      if (video?.srcObject) {
        video.srcObject = stream;
      }
      document.addEventListener(
        "WeixinJSBridgeReady",
        () => {
          alert("微信浏览器 ready");
          // 微信浏览器
          video.play();
        },
        false
      );
      // 自动播放
      document.addEventListener("touchstart", () => {
        try {
          video.play();
        } catch {}
      });
    })
    .catch(function (err) {
      console.log("err:", err);
      alert(err);
      /* 处理 error */
    });
});

const onFinished = () => {
  window.location.href = `https://ar.vtogether.net/arjfqzh/#/?content=${message.value}&color=${colorName.value}`;
};

const calculateSwipe = () => {
  if (!isFinished.value) return;
  const diffY = startY.value - endY.value;

  // 设置最小滑动距离阈值
  const minSwipeDistance = 50;

  if (Math.abs(diffY) > minSwipeDistance) {
    if (diffY > 0) {
      // 向上滑动
      handleSwipeUp();
    }
  }
};

const handleSwipeUp = () => {
  isFlying.value = true;
};

const onTouchStart = (event: any) => {
  startY.value = event.touches[0].clientY;
};

const onTouchEnd = (event: any) => {
  endY.value = event.changedTouches[0].clientY;
  calculateSwipe();
};

const updateView = (view: number) => {
  pageView.value = view;
};

const updateColor = (color: any) => {
  colorName.value = color.name;
  craneColor.value = color.color;
};
</script>

<style scoped lang="less">
/* 通用写法，覆盖所有浏览器 */
::placeholder {
  color: #e2be8b;
}
</style>
